package com.metagurukul.metaspace.actions;

import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.metagurukul.metaspace.controller.ChangePasswordForm;
import com.metagurukul.metaspace.models.beans.UserLoginDetail;
import com.metagurukul.metaspace.service.UserService;

/**
 * 
 * Represents an  Action class which helps in changing the password for the user.
 * This class redirect user to personalDetailsPage for success
 * 
 * 
 * @author himanshu
 * @see Action
 */
public class ChangePasswordAction extends Action {
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.struts.action.Action#execute(org.apache.struts.action.
	 * ActionMapping, org.apache.struts.action.ActionForm,
	 * javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws SQLException {
		ChangePasswordForm changePasswordForm = (ChangePasswordForm) form;
		String newPassword = changePasswordForm.getNewPassword();
		String oldPassword = changePasswordForm.getOldPassword();

		HttpSession session = request.getSession(true);
		int userId = (Integer) session.getAttribute("id");
		int flag = changePassword(userId, oldPassword, newPassword);
		if (flag > 0) {
			return mapping.findForward("success");
		} else if (flag == 0) {
			ActionMessages errors = new ActionMessages();
			errors.add("oldPasswordNotMatched", new ActionMessage(
					"error.oldPassword.invalid"));
			saveErrors(request, errors);
			return mapping.getInputForward();
		} else {
			ActionMessages errors = new ActionMessages();
			errors.add("oldPasswordNotMatched", new ActionMessage(
					"error.userId.invalid"));
			saveErrors(request, errors);
			return mapping.getInputForward();
		}
	}

	/**
	 * Uses UserService class to connect with Dao
	 *  
	 * @param userId
	 * @param oldPassword
	 * @param newPassword
	 * @return
	 * @throws SQLException
	 */
	public int changePassword(int userId, String oldPassword, String newPassword)
			throws SQLException {
		UserLoginDetail userLoginDetail = new UserLoginDetail();
		userLoginDetail.setUserId(userId);
		userLoginDetail.setPassword(newPassword);
		return UserService.updateUserLoginDetail(userLoginDetail, oldPassword);
	}
}
